package com.engr.core.service.member.impl;

import com.alibaba.fastjson.JSONObject;
import com.engr.core.enums.ResultCodeEnum;
import com.engr.core.service.member.MemberService;
import com.engr.core.util.ConfigProperties;
import com.engr.domain.Member;
import com.engr.domain.MemberLogin;
import com.engr.dto.MemberDto;
import com.engr.exception.ExceptionUtils;
import com.engr.repository.member.MemberLoginRepository;
import com.engr.repository.member.MemberRepository;
import com.engr.util.HttpClientUtils;
import com.engr.util.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @program: train-project
 * @description:
 * @author: lyx
 * @create: 2018-11-03
 **/
@Service
public class MemberServiceImpl implements MemberService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private MemberLoginRepository memberLoginRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ConfigProperties configProperties;

    @Override
    public boolean login(MemberDto memberDto, MemberLogin memberLogin) {

        memberLogin.setToken(this.generateToken());

        String emailOrUsernameOrPhone = memberDto.getUsername();
        String rawPassword = memberDto.getPassword();
        Optional<Member> optional = memberRepository.findByUsernameOrPhoneOrEmail(emailOrUsernameOrPhone);
        if (!optional.isPresent())
            ExceptionUtils.throwServiceException("用户不存在");

        Member member = optional.get();
        if (passwordEncoder.matches(rawPassword, member.getPassword())) {
            memberLogin.setUsername(member.getUsername());
            memberLogin.setNickname(member.getNickname());
            member.setLastLoginTime(new Date());
            memberLoginRepository.save(memberLogin);
            //memberDao.save(member);
            return true;
        }
        return false;
    }

    @Override
    public boolean getVcode(String ticket, String rendStr, HttpServletRequest request) {

        //MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("aid", configProperties.getCaptcahlAid());
        param.put("AppSecretKey", configProperties.getCaptcahlKey());
        param.put("Ticket", ticket);
        param.put("Randstr", rendStr);
        param.put("UserIP", ServletUtil.getIpAddr(request));

        String msg = HttpClientUtils.httpPostFormRequest(configProperties.getCaptcahlUrl(), param);
        JSONObject json = JSONObject.parseObject(msg);
        String result = (String) json.get("response");
        if(!ResultCodeEnum.EFFECTIVE.getCode().equals(result)){
            logger.error("腾讯验证码返回状态值,err_msg:-----------------------{}", json.getString("err_msg"), this.getClass().getClass());
            ExceptionUtils.throwServiceException(json.getString("err_msg"));
        }
        return true;
    }

    /**
     * 获取token
     * @author lyx
     * @return token
     */
    @Transactional(readOnly = true)
    public String generateToken() {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

}
